package com.xzuf.finance;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileNameExtensionFilter;

import net.miginfocom.swing.MigLayout;
import net.sf.nachocalendar.CalendarFactory;
import net.sf.nachocalendar.components.DateField;

import org.jdesktop.swingx.JXBusyLabel;
import org.jdesktop.swingx.JXDialog;
import org.jdesktop.swingx.JXTable;

import com.xzuf.core.vo.xml.DataSourceVO;
import com.xzuf.finance.txt.ExportTextFile;
import com.xzuf.plugin.IModulePlugin;
import com.xzuf.pub.DbUtils;
import com.xzuf.pub.FileUtils;
import com.xzuf.pub.GlobalValue;
import com.xzuf.pub.GuiUtils;
import com.xzuf.pub.UFDate;
import com.xzuf.pub.exception.ExportFileException;

/**
 * @author xzgf
 * @since 2008-8-13
 * @version 1.0
 */
public class MainUI extends JPanel implements IModulePlugin, ActionListener {

	private JButton btnQuery = new JButton("查询");

	private JButton btnExport = new JButton("导出");

	private JButton btnOk = new JButton("确定");

	private JButton btnCancel = new JButton("取消");

	private JDialog dialog = new JDialog(GlobalValue.mainFrame);

	private DateField startdateField = CalendarFactory.createDateField();

	private DateField enddateField = CalendarFactory.createDateField();

	private JLabel lb_result = new JLabel();

	private final static String sql = "select t1.dwdm,t1.dwmc,t2.jksbh,t2.jkrq,t2.jfr_mc,t2.skr_yhzh,t3.id,t3.xmdm,t3.zxmcode,t2.sfje,t3.pjh from pubkszl t1, nt_sftjsk t2, nt_sftjsmxk t3 where t1.dwdm = t2.dwdm and t2.dwdm = t3.dwdm and t2.jksbh = t3.jksbh  and t2.jkrq >=? and t2.jkrq <=? ";
	// private final static String sql =
	// "select t1.dwdm,t1.dwmc,t1.jksbh,t1.jkrq,t1.jfr_mc,t1.skr_yhzh,t1.id,t1.xmdm,t1.zxmcode,t1.sfje,t1.pjh from finance t1 where t1.jkrq >=? and t1.jkrq <=? "
	// ;

	private List<FinanceDataVO> dataList = new ArrayList<FinanceDataVO>();

//	private List<FinanceDataVO> trimDataList = new ArrayList<FinanceDataVO>();

	private JXTable dataTable = new JXTable();

	private FinanceTableModel model = null;

	private String[] strKeys = new String[] { "unitcode", "unitname", "jkcode","jkdate", "jkname", "bankno", "detailid", "projectcode","executecode", "money", "billno" };

	private String[] strNames = new String[] { "单位编码", "单位名称", "缴款号", "缴款日期","缴款人", "银行号", "明细ID", "项目编码", "执行码", "金额", "单据号" };

	private JXBusyLabel label = new JXBusyLabel();
	
	private JXDialog waiteFrame = new JXDialog(GlobalValue.mainFrame,label);

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int getCurrentOpState() {
		return 0;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void setCurrentOpState(int state) {
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public JPanel start() {
		
		waiteFrame.setTitle("财政局罚没收入导出工具...");
		waiteFrame.setLayout(new FlowLayout(FlowLayout.CENTER));
		waiteFrame.removeAll();
		waiteFrame.add(label);
		waiteFrame.setSize(new Dimension(280,100));
		waiteFrame.setModal(true);
		waiteFrame.setLocationRelativeTo(null);
		
		JPanel panel = new JPanel();
		panel.setLayout(new FlowLayout());

		btnQuery.addActionListener(this);
		btnExport.addActionListener(this);

		panel.add(btnQuery);
		panel.add(btnExport);
		panel.add(lb_result);

		JPanel dataPanel = new JPanel();
		dataPanel.setLayout(new BorderLayout());

		model = new FinanceTableModel();
		FinanceDataItem[] items = new FinanceDataItem[11];
		for (int i = 0; i < items.length; i++) {
			items[i] = new FinanceDataItem();
			items[i].setKey(strKeys[i]);
			items[i].setValue(strNames[i]);
		}

		model.setDataItemList(items);
		dataTable.setModel(model);
		dataTable.setColumnControlVisible(true);
		dataTable.setEditable(false);
		// dataTable.setDefaultRenderer(Number.class, new
		// DefaultTableRenderer(FormatStringValue
		// .NUMBER_TO_STRING,JLabel.RIGHT));
		// dataTable.setDefaultRenderer(Date.class, new
		// DefaultTableRenderer(FormatStringValue.DATE_TO_STRING));
		dataTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		dataTable.getTableHeader().setReorderingAllowed(false); // ���ò����ƶ���������������
		dataPanel.add(new JScrollPane(dataTable), BorderLayout.CENTER);

		setLayout(new BorderLayout());
		add(panel, BorderLayout.NORTH);
		add(dataPanel, BorderLayout.CENTER);
		return this;
	}

	private void onOk() {

		if (startdateField.getValue() == null || enddateField.getValue() == null) {
			GuiUtils.showMessage("条件为空..", GlobalValue.mainFrame);
			return;
		}

		refreshData();
	}

	private void refreshData() {
		try {
			GlobalValue.sysProp = FileUtils.getSystemPropertyFromXML(GlobalValue.CONFIG_FILE_BAT);
			DataSourceVO dataSourceVO = GlobalValue.DefaultDataSource;
			Connection conn = DbUtils.createDbConnection(dataSourceVO);
			PreparedStatement pstmt = conn.prepareStatement(sql);
			Date sdate = (Date) startdateField.getValue();
			Date edate = (Date) enddateField.getValue();
			UFDate startDate = new UFDate(sdate);
			UFDate endDate = new UFDate(edate);
			String str1 = startDate.getYear() + startDate.getStrMonth() + startDate.getStrDay();
			String str2 = endDate.getYear() + endDate.getStrMonth() + endDate.getStrDay();
			pstmt.setString(1, str1);
			pstmt.setString(2, str2);
			ResultSet rs = pstmt.executeQuery();
			dataList = new ArrayList<FinanceDataVO>();
			if (rs != null) {
				FinanceDataVO vo = null;
//				FinanceDataVO vo2 = null;
				while (rs.next()) {
					vo = new FinanceDataVO();
					vo.setUnitcode(rs.getString(1));
					vo.setUnitname(rs.getString(2));
					vo.setJkcode(rs.getString(3));
					vo.setJkdate(rs.getString(4));
					vo.setJkname(rs.getString(5));
					vo.setBankno(rs.getString(6));
					vo.setDetailid(rs.getString(7));
					vo.setProjectcode(rs.getString(8));
					vo.setExecutecode(rs.getString(9));
					vo.setMoney(rs.getString(10));
					vo.setBillno(rs.getString(11));
					dataList.add(vo);
//					vo2 = new FinanceDataVO();
//					if(vo.getUnitcode() != null)
//						vo2.setUnitcode(vo.getUnitcode().trim());
//					if(vo.getUnitname() != null)
//						vo2.setUnitname(vo.getUnitname().trim());
//					if(vo.getJkcode() != null) 
//						vo2.setJkcode(vo.getJkcode().trim());
//					if(vo.getJkdate() != null)
//						vo2.setJkdate(vo.getJkdate().trim());
//					if(vo.getJkname() != null) 
//						vo2.setJkname(vo.getJkname().trim());
//					if(vo.getBankno() != null) 
//						vo2.setBankno(vo.getBankno().trim());
//					if(vo.getDetailid() != null)
//						vo2.setDetailid(vo.getDetailid().trim());
//					if(vo.getProjectcode() != null)
//						vo2.setProjectcode(vo.getProjectcode().trim());
//					if(vo.getExecutecode() != null)
//						vo2.setExecutecode(vo.getExecutecode().trim());
//					if(vo.getMoney() != null) 
//						vo2.setMoney(vo.getMoney().trim());
//					if(vo.getBillno() != null)
//						vo2.setBillno(vo.getBillno().trim());
//					trimDataList.add(vo2);
				}
			}

			FinanceDataVO[] dataVOs = dataList.toArray(new FinanceDataVO[0]);
			((FinanceTableModel) dataTable.getModel()).setBodyDataVO(dataVOs);
			lb_result.setText("导出成功,共[" + dataList.size() + "]条记录,查询条件:[" + startDate + "至" + endDate + "]");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			dialog.dispose();
		}
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == btnQuery) {
			onQuery();
		}
		if (e.getSource() == btnExport) {
			onExport();
		}

		if (e.getSource() == btnOk) {
			
			Thread waiteThread = new Thread() {
				@Override
				public void run() {
//					label.setBusy(true);
//					waiteFrame.setVisible(true);
					onOk();
				}
			};
			
			SwingUtilities.invokeLater(waiteThread);
//			dialog.dispose();
		}

		if (e.getSource() == btnCancel) {
			dialog.dispose();
		}
	}

	private void onQuery() {

		dialog.setTitle("查询条件");
		dialog.setSize(new Dimension(300, 200));
		dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		dialog.setLocationRelativeTo(null);
		dialog.setModal(true);
		JLabel lb_start = new JLabel("开始日期");

		JLabel lb_end = new JLabel("结束日期");
		btnOk.addActionListener(this);
		btnCancel.addActionListener(this);

		startdateField.setPreferredSize(new Dimension(100, 22));
		enddateField.setPreferredSize(new Dimension(100, 22));

		JPanel panel = new JPanel();
		panel.setLayout(new MigLayout());
		panel.add(lb_start, "cell 0 0");
		panel.add(startdateField, "cell 1 0");
		panel.add(lb_end, "cell 2 0");
		panel.add(enddateField, "cell 3 0");
		panel.add(btnOk, "cell 0 1");
		panel.add(btnCancel, "cell 1 1");
		dialog.setContentPane(panel);
		dialog.setVisible(true);
	}

	private List<String> getDataFromUI() {
		List<String> list = new ArrayList<String>();
		if (dataList != null && dataList.size() > 0) {
			Iterator<FinanceDataVO> iter = dataList.iterator();
			FinanceDataVO vo = null;
			String str = "";
			while (iter.hasNext()) {
				vo = iter.next();
				str = vo.getUnitcode() + ",";
				str = str + vo.getUnitname() + ",";
				str = str + vo.getJkcode() + ",";
				str = str + vo.getJkdate() + ",";
				str = str + vo.getJkname() + ",";
				str = str + vo.getBankno() + ",";
				str = str + vo.getDetailid() + ",";
				str = str + vo.getProjectcode() + ",";
				str = str + vo.getExecutecode() + ",";
				str = str + vo.getMoney() + ",";
				str = str + vo.getBillno();
				list.add(str);

			}
		}
		return list;
	}

	private void onExport() {

		JFileChooser filechooser = new JFileChooser(System.getProperty("user.home"));
		FileNameExtensionFilter filter = new FileNameExtensionFilter("TextFile", "txt");
		filechooser.setFileFilter(filter);
		IExportFileDesc exportFile = null;
		File descFile = null;
		int flag = filechooser.showSaveDialog(this);
		if (flag == JFileChooser.APPROVE_OPTION) {
			descFile = filechooser.getSelectedFile();
		}
		if (descFile == null) {
			return;
		}
		String fileName = descFile.getAbsolutePath();
		if (fileName.indexOf(".") == -1 && (!new File(fileName + ".txt").exists())) {
			fileName += ".txt";
		}

		try {
			exportFile = new ExportTextFile(getDataFromUI());
			exportFile.doIt(new File(fileName));
		} catch (ExportFileException e) {
			GuiUtils.showMessage(e.getMessage(), this);
		}
	}

}
